package com.DAO.Impl;

import com.DAO.StudentDAO;
import com.DBUtil.DBUtil;
import com.entity.Student;
import com.entity.stuAndMenu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 20x
 * @date 2024 - 12 -12
 **/
public class StudentDAOImpl implements StudentDAO {
    @Override
    public Student getStudentById(String id) {
        Student stu = null;
        String sql = "select * from student where stuId =?";
        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection conn = DBUtil.getConnection();
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1, id);
            rs = pst.executeQuery();
            if (rs.next()) {
                stu = new Student(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7));
            }
            DBUtil.close(rs,pst,conn);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return stu;
    }

    @Override
    public List<stuAndMenu> getStudentAndMenuById(String Stuid) {
        List<stuAndMenu> list = null;
        String sql = "select * from menuAndStu where stuId = ?";
        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection conn = DBUtil.getConnection();
        try {
            pst = conn.prepareStatement(sql);
            pst.setString(1, Stuid);
            rs = pst.executeQuery();
            list = new ArrayList<>();
            while (rs.next()) {
                  stuAndMenu stuAndMenu = new stuAndMenu(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5));
                  list.add(stuAndMenu);
            }
            DBUtil.close(rs,pst,conn);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Student> ListStudent() {
        List<Student> list = new ArrayList<>();
        String sql = "select * from student";
        ResultSet rs = null;
        PreparedStatement pst = null;
        Connection conn = DBUtil.getConnection();
        try {
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            while (rs.next()) {
                Student stu = new Student(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7));
                list.add(stu);
            }
            DBUtil.close(rs,pst,conn);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static void main(String[] args) {
        StudentDAOImpl stu = new StudentDAOImpl();
//        System.out.println(stu.getStudentById("S001"));
//        System.out.println(stu.getStudentAndMenuById("S001"));
        System.out.println(stu.ListStudent());
    }

}
